<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//引入livecourse模型类
use App\Http\Models\Livecourse;
//引入Stream模型类
use App\Http\Models\Stream;
use Illuminate\Support\Facades\Validator;
class LivecourseController extends Controller
{
    //课程直播显示
    public function index(Request $request){
        if($request->isMethod('post')){

            $cnt = Livecourse::count();
//            $data = Livecourse::with('stream')->get();
            //数据分页信息
            //偏移量(第几页)
            $offset = $request->input('start');
            //显示数据的条数
            $len = $request->input('length');

            //进行排序的数据
            $n =  $request->input('order.0.column');//获取进行排序字段的列号
            $ofield = $request->input('columns.'.$n.'.data');//获取进行排序的字段
            $order = $request->input('order.0.dir');//进行排序的顺序（asc|desc）

            //进行模糊检索的数据
            $searchVal = $request->input('search.value');//获取进行模糊查询的数据
            $data = Livecourse::offset($offset)
                ->limit($len)
                ->orderBy($ofield,$order)
                ->where('name','like',"%$searchVal%")
                ->with("stream")
                ->get();
            foreach($data as $val){
                $val['start_at'] = date('Y-m-d H:i:s',$val['start_at']);
                $val['end_at'] = date('Y-m-d H:i:s',$val['end_at']);
            }
            //datatable 需要返回的数据格式
            $info = [
                'draw'=>$request->input('draw'),
                'recordsTotal'=>$cnt,
                'recordsFiltered'=>$cnt,
                'data'=>$data
            ];
            return $info;
        }

        return view('admin.livecourse.index',compact('data'));
    }

    public function add(Request $request){
        if($request->isMethod('post')){
            //获取post提交的所有数据
            $data = $request->all();

            //自定义验证规则
            $rules = [
                'name'      => 'required|unique:live_course',
                'stream_id' => 'not_in:0|numeric',
            ];
            $notices = [
                'name.required'       => '直播课程不能为空',
                'name.unique'        => '该直播课程已存在',
                'stream_id.not_in'   => '直播流不存在',
                'stream_id.numeric'  => '直播流不合法',
            ];
            $validator = Validator::make($data,$rules,$notices);
            if($validator->passes()){
                $data['start_at'] = strtotime($data['start_at']);
                $data['end_at'] = strtotime($data['end_at']);
                $result = Livecourse::create($data);
                if($result){
                    return ['success'=>true];
                }else{
                    return ['success'=>'数据添加失败'];
                }

            }else{
                $errorinfo = collect($validator->messages())->implode('0','|');
                return ['success'=>false,'errorinfo'=>$errorinfo];
            }

            
        }
        //获取直播流名称
        $res = Stream::pluck('stream_name','stream_id');
//        dd($res);
        return view('admin.livecourse.add',compact('res'));
    }

    //直播课程编辑
    public function edit(Request $request,Livecourse $livecourse){
        if($request->isMethod('post')){
            $data = $request->all();
            //验证数据
            $rules = [
                'name'  =>  'required',

            ];
            $notices = [
                'name.required' => '直播课程名称不能为空',
            ];
            $validator = Validator::make($data,$rules,$notices);
            if($validator->passes()){
                $data['start_at'] = strtotime($data['start_at']);
                $data['end_at'] = strtotime($data['end_at']);
                //更新当前查出来的数据
                $res = $livecourse->update($data);
                if($res){
                    return ['success'=>true];
                }else{
                    return ['success'=>false,'errorinfo'=>'数据更新失败'];
                }
            }else{
                $errorinfo = collect($validator->messages())->implode('0','|');
                return ['success'=>false,'errorinfo'=>$errorinfo];
            }
        }

        $stream = Stream::pluck('stream_name','stream_id');
            $livecourse['start_at'] = date('Y-m-d H:i:s',$livecourse['start_at']);
            $livecourse['end_at'] = date('Y-m-d H:i:s',$livecourse['end_at']);
        return view('admin.livecourse.edit',compact('livecourse','stream'));
    }

    //获取直播流

    public function getpush(Livecourse $livecourse,Stream $stream){
        //直播的主机地址
        $host        = "pili-publish.www.vizt.top";
        //直播空间名
        $space       = "live_streaming01";
        //直播流名
        $stream_name = $stream->stream_name;
        //直播过期时间
        $e           = $livecourse->end_at;
        //制作鉴权
        $path        =  "/$space/$stream_name?e=$e";//鉴权格式
        //获取access_key 和 secret_key
        //通过功能包类实现鉴权制作
        $ak          = config('filesystems.disks.qiniu.access_key');
        $sk          = config('filesystems.disks.qiniu.secret_key');
        //实例化qiniu下的Auth类
        //vendor/qiniu/php-sdk/src/Qiniu/Auth.php
        $auth = new \Qiniu\Auth($ak,$sk);

        $token = $auth->sign($path);

        //拼装推流地址
        return "rtmp://$host/$space/$stream_name?e=$e&token=$token";
    }
}
